package com.fl.nj.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文件操作工具类
 * 提供数据保存到文件和从文件读取数据的功能
 */
public class FileUtil {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 将数据列表保存到JSON文件中
     * @param filePath 文件路径
     * @param dataList 数据列表
     * @throws IOException IO异常
     */
    public static void saveDataToJsonFile(String filePath, List<Map<String, Object>> dataList) throws IOException {
        // 确保目录存在
        File file = new File(filePath);
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }

        // 写入JSON数据
        OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(file, dataList);
    }

    /**
     * 从JSON文件中读取数据列表
     * @param filePath 文件路径
     * @return 数据列表
     * @throws IOException IO异常
     */
    public static List<Map<String, Object>> readDataFromJsonFile(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IOException("文件不存在: " + filePath);
        }

        return OBJECT_MAPPER.readValue(file, new TypeReference<List<Map<String, Object>>>() {});
    }

    /**
     * 将数据保存到CSV文件中
     * @param filePath 文件路径
     * @param dataList 数据列表
     * @throws IOException IO异常
     */
    public static void saveDataToCsvFile(String filePath, List<Map<String, Object>> dataList) throws IOException {
        if (dataList.isEmpty()) {
            return;
        }

        // 确保目录存在
        File file = new File(filePath);
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }

        // 获取表头
        Map<String, Object> firstRow = dataList.get(0);
        String header = String.join(",", firstRow.keySet());

        // 构建CSV内容
        StringBuilder csvContent = new StringBuilder(header + "\n");
        for (Map<String, Object> row : dataList) {
            String rowData = row.values().stream()
                    .map(value -> value == null ? "" : value.toString())
                    .map(value -> value.contains(",") ? "\"" + value + "\"" : value)
                    .collect(Collectors.joining(","));
            csvContent.append(rowData).append("\n");
        }

        // 写入文件
        Files.write(Paths.get(filePath), csvContent.toString().getBytes());
    }
}